package com.chat.websocket.aspect;

import com.chat.websocket.util.ip2region.Ip2regionUtil;
import com.chat.websocket.util.useragent.UserAgentUtil;
import cz.mallat.uasparser.UserAgentInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * SunJingxuan
 * 2022 \ 07 \ 28
 */
@Component
@Slf4j
public class IpAddressAspect {

    @Resource
    private Ip2regionUtil ip2regionUtil;

    public Map<String, Object> login() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            String userAgent = request.getHeader("user-agent");
            UserAgentInfo userAgentInfo = UserAgentUtil.UA_SPARSER.parse(userAgent);
            log.info("操做系统名称: {}", userAgentInfo.getOsFamily());
            log.info("操做系统: {}", userAgentInfo.getOsName());
            log.info("浏览器版本: {}", userAgentInfo.getBrowserVersionInfo());
            log.info("设备类型: {}", userAgentInfo.getDeviceType());
            log.info("浏览器: {}", userAgentInfo.getUaName());
            log.info("类型: {}", userAgentInfo.getType());
            String ip = ip2regionUtil.getIp();
            final Map<String, Object>[] ipTerritory = new Map[]{null};
            Optional.ofNullable(ip).ifPresent(ipAddress -> {
                ipTerritory[0] = ip2regionUtil.getIPTerritory(ipAddress);
            });
            ipTerritory[0].put("equipmentType", userAgentInfo.getOsFamily());
            return ipTerritory[0];
        } catch (NullPointerException e) {
            log.error("获取设备信息异常", e);
            return null;
        } catch (Throwable e) {
            log.error("获取ip地址异常", e);
            return null;
        }
    }
}
